//
//  TCMsgListCell.m
//  TCLVBIM
//
//  Created by zhangxiang on 16/8/9.
//  Copyright © 2016年 tencent. All rights reserved.
//

#import "TCMsgListCell.h"
#import "TCUtil.h"

#import "UIView+LZCView.h"
#import "LZCAlertView.h"
#import "LZCTools.h"

static NSMutableArray      *_arryColor;
static NSInteger           _index = 0;

@implementation TCMsgListCell
{
    UIButton *_levelBtn;
    UIView  *_msgView;
    UILabel *_msgLabel;
//    UIImageView *_msgBkView;
}
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        _msgView  = [[UIView alloc] initWithFrame:CGRectZero];
        _msgView.backgroundColor = RGBA(0, 0, 0, 0.3);
//        _msgBkView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"piece"]];

//        [_msgView addSubview:_msgBkView];
//        [_msgView sendSubviewToBack:_msgBkView];
        
        _msgView.layer.cornerRadius = 10;
        _msgView.layer.masksToBounds = YES;
        
        _levelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_msgView addSubview:_levelBtn];
        _levelBtn.userInteractionEnabled = NO;
        [_levelBtn setBackgroundImage:[UIImage imageNamed:@"level_bg"] forState:UIControlStateNormal];
        [_levelBtn setImage:[UIImage imageNamed:@"level_star"] forState:UIControlStateNormal];
        _levelBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_levelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        
        _msgLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _msgLabel.numberOfLines = 0;
        _msgLabel.font = [UIFont systemFontOfSize:MSG_TABLEVIEW_LABEL_FONT];

        [_msgView addSubview:_msgLabel];
        [self.contentView addSubview:_msgView];
    }
    return self;
}
 
-(void)layoutSubviews{
    CGSize vipSize;
    if (!_levelBtn.isHidden) {
        vipSize = [LZCTools textSizeWithText:@"x" font:[UIFont systemFontOfSize:14]];
        _levelBtn.frame = CGRectMake(5, 2, 5+vipSize.width+vipSize.height, vipSize.height-4);
        _msgLabel.frame = CGRectMake(15+vipSize.width+vipSize.height, 0, _msgLabel.width, _msgLabel.height);
        _msgView.frame  = CGRectMake(0, 0, vipSize.width+vipSize.height+_msgLabel.width + 20, _msgLabel.height);
    }
    else {
        _msgLabel.frame = CGRectMake(5, 0, _msgLabel.width, _msgLabel.height);
        _msgView.frame  = CGRectMake(0, 0, _msgLabel.width + 10, _msgLabel.height);
    }
    
    _msgView.layer.cornerRadius = 5;
    _msgView.layer.masksToBounds = YES;
//    _msgBkView.frame = _msgView.frame;
}

-(void)refreshWithModel:(TCMsgModel *)msgModel{
    
    if (msgModel.level==nil) {
        _levelBtn.hidden = YES;
    }
    else
        _levelBtn.hidden = NO;
    [_levelBtn setTitle:msgModel.level forState:UIControlStateNormal];
    _msgLabel.attributedText = msgModel.msgAttribText;
    _msgLabel.width = MSG_TABLEVIEW_WIDTH - 20;
    [_msgLabel sizeToFit];
	
	/*
	if ([msgModel.is_robot isEqualToString:@"1"]) {
		[LZCTools HUDMessage:@"抱歉，该用户设置了隐私设定" delay:1.0];
		return;
	}
	 */
	
    // 主播发文本消息没有穿id等信息
    if (msgModel.userId.length) {
        __weak typeof(self) weakSelf = self;
        [_msgView addActionWithblock:^{
            
            // GET /lives/viewers/{id} 获取单个观众信息 id *要查询的用户ID ? anchor_id *主播ID
            
            NSString *url = [NSString stringWithFormat:@"%@/%@", APIViewers, msgModel.userId];
            
            NSLog(@"%@", GetUserDefaule(CURRLIVE));
            
            [[NetworkTool sharedTool] requestWithName:@"直播间获取用户信息" URLString:url parameters:@{@"anchor_id":[GetUserDefaule(CURRLIVE) valueForKey:@"hostId"]} method:@"GET" callBack:^(id responseObject) {
                
                NSDictionary *userDict = [responseObject valueForKey:@"data"];
                
                UIViewController *currVC = [weakSelf topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
                
                LZCAlertView *alert = [[LZCAlertView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
                [alert initShow:userDict];
                [currVC.view addSubview:alert];
            }];
        }];
    }
    
    
    
}

+(NSAttributedString *)getAttributedStringFromModel:(TCMsgModel *)msgModel{
     _arryColor = [[NSMutableArray alloc] initWithObjects:UIColorFromRGB(0x1fbcb6),UIColorFromRGB(0x2b7de2),UIColorFromRGB(0xff7906),nil];

    NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] init];
    if (msgModel.msgType == TCMsgModelType_NormalMsg || msgModel.msgType == TCMsgModelType_DanmaMsg)
    {
        NSMutableAttributedString *userName = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ ", msgModel.userName]];
        [attribute appendAttributedString:userName];
        
        NSMutableAttributedString *userMsg = [[NSMutableAttributedString alloc] initWithString:msgModel.userMsg];
        [attribute appendAttributedString:userMsg];
        
        [attribute addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:MSG_TABLEVIEW_LABEL_FONT] range:NSMakeRange(0,attribute.length)];
        
        _index = _index % [_arryColor count];
        [attribute addAttribute:NSForegroundColorAttributeName value:[_arryColor objectAtIndex:_index] range:NSMakeRange(0,userName.length)];
        [attribute addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(userName.length, userMsg.length)];
        _index++;
    }
    else
    {
        NSMutableAttributedString *msgShow = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"通知 %@%@", msgModel.userName, msgModel.userMsg]];
        [attribute appendAttributedString:msgShow];
        [attribute addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:MSG_TABLEVIEW_LABEL_FONT] range:NSMakeRange(0, attribute.length)];
        [attribute addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:241/255.0 green:43/255.0 blue:91/255.0 alpha:1] range:NSMakeRange(0, msgShow.length)];
    }
    
    
    return attribute;
}
@end

#import "UIImage+Additions.h"
#import "UIView+CustomAutoLayout.h"

@implementation TCShowLiveTopView
{
    UIImageView          *_hostImage;        // 主播头像
    UIImageView          *_durationImage;    // 直播时长
    UILabel              *_durationLabel;
    UILabel              *_audienceLabel;    // 在线观众数
    UIButton             *_focusBtn;          // 关注
    
    NSTimer              *_timer;
    NSInteger            _startTime;
    NSInteger            _liveDuration;      // 直播时长
    NSInteger            _audienceCount;     // 在线观众数
    NSInteger            _likeCount;         // 点赞数
    NSInteger            _totalViewerCount;  // 总共观看人数
    
    BOOL                 _isHost;            // 是否是主播
    NSString             *_hostNickName;     // 主播昵称
    NSString             *_hostFaceUrl;      // 头像地址
    
    NSString             *_isVip;             // 是否是VIP
    NSString             *_isLike;             // 是否关注
    NSString             *_hostId;            // 直播id
    
    
}

- (instancetype)initWithFrame:(CGRect)frame isHost:(BOOL)isHost hostNickName:(NSString *)hostNickName audienceCount:(NSInteger)audienceCount likeCount:(NSInteger)likeCount hostFaceUrl:(NSString *)hostFaceUrl isVIP:(NSString *)isVIP isLike:(NSString *)isLike hostId:(NSString *)hostId roomId:(NSString *)roomId {
    if (self = [super initWithFrame: frame]) {
//        _audienceCount = audienceCount;
        _totalViewerCount = audienceCount;
        _likeCount = likeCount;
        _liveDuration = 0;

        _isHost = isHost;
        _hostNickName = hostNickName;
        _hostFaceUrl = hostFaceUrl;
        _isVip = isVIP;
        _isLike = isLike;
        _hostId = hostId;
        
        self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
        self.layer.cornerRadius = frame.size.height / 2;
        self.layer.masksToBounds = YES;
        
        [self initUI];
    }
    return self;
}

- (void)setViewerCount:(int)viewerCount likeCount:(int)likeCount
{
    _audienceCount = viewerCount;
    _totalViewerCount = viewerCount;
    _likeCount = likeCount;
    [_audienceLabel setText:[NSString stringWithFormat:@"%ld", _audienceCount]];
}

- (void)initUI {
    _hostImage = [[UIImageView alloc] init];
    _hostImage.layer.cornerRadius = (self.frame.size.height - 2) / 2;
    _hostImage.layer.masksToBounds = YES;
    _hostImage.layer.borderWidth = 1;
    _hostImage.layer.borderColor = [UIColor whiteColor].CGColor;
//    [_hostImage sd_setImageWithURL:[NSURL URLWithString:[TCUtil transImageURL2HttpsURL:_hostFaceUrl]] placeholderImage:[UIImage imageNamed:@"default_user"]];
    [_hostImage sd_setImageWithURL:[NSURL URLWithString:_hostFaceUrl] placeholderImage:[UIImage imageNamed:@"placeHolder.png"]];
    [self addSubview:_hostImage];
    
        _durationLabel = [[UILabel alloc] init];
    if (_isHost) {
        _durationImage = [[UIImageView alloc] init];
        _durationImage.image = [UIImage imageNamed:@"dot"];
        [self addSubview:_durationImage];
        
        [_durationLabel setText:@"00:00:00"];
    }
    else {
        [_durationLabel setText:_hostNickName];
    }
    _durationLabel.font = [UIFont boldSystemFontOfSize:10];
    _durationLabel.textColor = [UIColor whiteColor];
    [self addSubview:_durationLabel];
    
    
    _audienceLabel = [[UILabel alloc] init];
    [_audienceLabel setText:[NSString stringWithFormat:@"%ld", _audienceCount]];
    _audienceLabel.font = [UIFont boldSystemFontOfSize:10];
    _audienceLabel.textColor = [UIColor whiteColor];
    [self addSubview:_audienceLabel];
    
    
    // relayout
    [_hostImage sizeWith:CGSizeMake(33, 33)];
    [_hostImage layoutParentVerticalCenter];
    [_hostImage alignParentLeftWithMargin:1];
    
    if (_isHost) {
        [_durationImage sizeWith:CGSizeMake(5, 5)];
        [_durationImage alignParentTopWithMargin:7.5];
        [_durationImage layoutToRightOf:_hostImage margin:5];
        
        [_durationLabel sizeWith:CGSizeMake(48, 10)];
        [_durationLabel alignParentTopWithMargin:5];
        [_durationLabel layoutToRightOf:_durationImage margin:2.5];
    }
    else {
        [_durationLabel sizeWith:CGSizeMake(48, 10)];
        [_durationLabel alignParentTopWithMargin:5];
        [_durationLabel layoutToRightOf:_hostImage margin:10];
    }

    [_audienceLabel sameWith:_durationLabel];
    [_audienceLabel alignParentBottomWithMargin:5];
    
    UIImageView *vipImg = [[UIImageView alloc] initWithFrame:CGRectMake(_hostImage.x+_hostImage.width-_hostImage.width/3, _hostImage.x+_hostImage.width-_hostImage.width/3, _hostImage.width/3, _hostImage.width/3)];
    [self addSubview:vipImg];
    if ([_isVip isEqualToString:@"1"]) {
        vipImg.image = IMAGE(@"");
    }
    else if ([_isVip isEqualToString:@"2"]) {
        vipImg.image = IMAGE(@"icon_add_v");
    }
    else if ([_isVip isEqualToString:@"3"]) {
        vipImg.image = IMAGE(@"icon_add_v_expert");
    }
    
    _focusBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self addSubview:_focusBtn];
    _focusBtn.backgroundColor = [UIColor redColor];
    if ([_isLike isEqualToString:@"1"]) {
        [_focusBtn setTitle:@"取消" forState:UIControlStateNormal];
    }
    else
        [_focusBtn setTitle:@"关注" forState:UIControlStateNormal];
    
    if (_isHost) {
        _focusBtn.hidden = YES;
    }
    else {
        _focusBtn.hidden = NO;
    }
    
    _focusBtn.backgroundColor = UIMainColorRGB;
    _focusBtn.titleLabel.font = kUHSystemFontWithSize(14);
    _focusBtn.frame = CGRectMake(self.width-2-50, SW(80), 50, self.height-SW(40));
    _focusBtn.layer.cornerRadius = (self.height-SW(40))/2;
    _focusBtn.layer.masksToBounds = YES;
    [_focusBtn addTarget:self action:@selector(clickFocus:) forControlEvents:UIControlEventTouchUpInside];
    

    [_hostImage addTarget:self action:@selector(clickHostImage:)];
    

    
}

- (void)startLive {
    if (_isHost) {
        _startTime = (NSInteger)[[NSDate date] timeIntervalSince1970];
        
        if (_timer) {
            [_timer invalidate];
        }
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onLiveTimer) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    }
}

- (void)pauseLive {
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}

- (void)resumeLive {
    [self startLive];
}

- (NSInteger)getViewerCount {
    return _audienceCount;
}

- (NSInteger)getLikeCount {
    return _likeCount;
}

- (NSInteger)getTotalViewerCount {
    return _totalViewerCount;
}

- (NSInteger)getLiveDuration {
    return _liveDuration;
}

- (void)onLiveTimer {
    NSInteger curTime = (NSInteger)[[NSDate date] timeIntervalSince1970];
    NSInteger dur = curTime - _startTime;
    
    NSString *durStr = nil;
    int h = (int)dur/3600;
    int m = (int)(dur - h *3600)/60;
    int s = (int)dur%60;
    durStr = [NSString stringWithFormat:@"%02d:%02d:%02d", h, m, s];
    
    _liveDuration = dur;
    [_durationLabel setText:durStr];
}

- (void)onUserEnterLiveRoom {
    _audienceCount ++;
    _totalViewerCount ++;
    [_audienceLabel setText:[NSString stringWithFormat:@"%ld", _audienceCount]];
}

- (void)onUserExitLiveRoom {
    if (_audienceCount > 0) {
        _audienceCount --;
    }
    [_audienceLabel setText:[NSString stringWithFormat:@"%ld", _audienceCount]];
}

- (void)onUserSendLikeMessage {
    _likeCount ++;
}

- (void)clickFocus:(UIButton *  )sender {
    
    NSString *toId = _hostId;
    
    if ([sender.titleLabel.text isEqualToString:@"关注"]) {
        [[NetworkTool sharedTool] requestWithName:@"关注" URLString:APIFavorites parameters:@{@"to":toId} method:@"POST" callBack:^(id responseObject) {
            [sender setTitle:@"取消" forState:UIControlStateNormal];
            // 如果是主播，就发送通知，让主播显示某人关注了他
            NSDictionary *infoDict = @{@"imId":_hostId,
                                       @"uid":_hostId,
                                       @"nickname":_hostNickName,
                                       @"headpic":_hostFaceUrl,
                                       @"level":@"0"}; // 没有获取等级
            
            NSError *parseError = nil;
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:infoDict options:NSJSONWritingPrettyPrinted error:&parseError];
            NSString *infoStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            
            // 发送私聊消息通知
            NSNotification *notification =[NSNotification notificationWithName:@"SendFavoritesMsg" object:nil userInfo:@{@"receiveInfo":infoStr}];
            //通过通知中心发送通知
            [[NSNotificationCenter defaultCenter] postNotification:notification];
        }];
    }
    else {
        NSString *url = [NSString stringWithFormat:@"%@/%@", APIFavorites, toId];
        [[NetworkTool sharedTool] requestWithName:@"取消关注" URLString:url parameters:nil method:@"DELETE" callBack:^(id responseObject) {
            [sender setTitle:@"关注" forState:UIControlStateNormal];
        }];
    }
}

- (void)clickHostImage:(id)sender {
    
    // 主播自己不可以点击主播头像
    if (![_hostId isEqualToString:[GetUserDefaule(USERINFO) valueForKey:@"user_id"]]) {
        
        [[NetworkTool sharedTool] requestWithName:@"获取用户信息" URLString:APIUser parameters:@{@"uid":_hostId} method:@"GET" callBack:^(id responseObject) {
            
            NSDictionary *userDict = [responseObject valueForKey:@"data"];
            
            UIViewController *currVC = [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
            
            LZCAlertView *alert = [[LZCAlertView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
			alert.isHostClicked = YES;
            [alert initShow:userDict];
            [currVC.view addSubview:alert];
            
        }];
    }
    
}


@end


#pragma mark 观众列表

@implementation TCAudienceListCell {
    UIImageView *_headPic;
    UIImageView *_imageVip;
}

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        _headPic = [[UIImageView alloc] initWithFrame:CGRectZero];
        _headPic.userInteractionEnabled = YES;
        _headPic.transform = CGAffineTransformMakeRotation(M_PI / 2);
        [self.contentView addSubview:_headPic];
        _imageVip = [[UIImageView alloc] initWithFrame:CGRectMake(_headPic.x+_headPic.width-_headPic.width/3, _headPic.x+_headPic.width-_headPic.width/3, _headPic.width/3, _headPic.width/3)];
        [self.contentView addSubview:_imageVip];
    }
    return self;
}

-(void)layoutSubviews{
    _headPic.frame = CGRectMake(0, 0, IMAGE_SIZE, IMAGE_SIZE);
    _headPic.layer.cornerRadius = _headPic.size.width/2;
    _headPic.clipsToBounds = YES;
	_imageVip.frame = CGRectMake(0, _headPic.x+_headPic.width-_headPic.width/3, _headPic.width/3, _headPic.width/3);
	_imageVip.transform = CGAffineTransformMakeRotation(M_PI / 2);
	[self.contentView bringSubviewToFront:_imageVip];
}

-(void)refreshWithModel:(TCUserInfoData *)msgModel{
    
     [_headPic sd_setImageWithURL:[NSURL URLWithString:msgModel.faceURL] placeholderImage:[UIImage imageNamed:@"placeHolder"]];
    
    if ([msgModel.isVip isEqualToString:@"1"]) {
		_imageVip.image = IMAGE(@"icon_add_v");
		NSLog(@"i was here to add V");
    }
	else {
		NSLog(@" not v");
        _imageVip.image = [UIImage imageNamed:@""];
	}
    
    __weak typeof(self) weakSelf = self;
    [_headPic addActionWithblock:^{
        NSLog(@"%@", msgModel);
        
        // GET /lives/viewers/{id} 获取单个观众信息 id *要查询的用户ID ? anchor_id *主播ID
        
        NSString *url = [NSString stringWithFormat:@"%@/%@", APIViewers, msgModel.identifier];
        
        NSLog(@"%@", GetUserDefaule(CURRLIVE));
		
		if ([msgModel.is_robot isEqualToString:@"1"]) {
			[LZCTools HUDMessage:@"抱歉，该用户设置了隐私设定" delay:1.0];
			return;
		}
		
		//点击自己头像不弹窗
		NSString *selfID = GetUserDefaule(USERINFO)[@"user_id"];
		if ([msgModel.uid isEqualToString:selfID]){
			return;
		}
        
        [[NetworkTool sharedTool] requestWithName:@"直播间获取用户信息" URLString:url parameters:@{@"anchor_id":[GetUserDefaule(CURRLIVE) valueForKey:@"hostId"]} method:@"GET" callBack:^(id responseObject) {
            
            NSDictionary *userDict = [responseObject valueForKey:@"data"];
            
            UIViewController *currVC = [weakSelf topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
            
            LZCAlertView *alert = [[LZCAlertView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
            [alert initShow:userDict];
            [currVC.view addSubview:alert];
        }];
    }];

}
@end
